package com.copa.l989;

import java.util.LinkedList;
import java.util.List;

/**
 * @author copa
 * @createDate 2022-07-07 18:42
 * @function 链表逐位相加（k转换字符串）
 */
public class Test1 {

    public List<Integer> addToArrayForm(int[] num, int k) {
        int kLength = String.valueOf(k).length();
        int maxLength = kLength >= num.length ? kLength : num.length;
        LinkedList<Integer> result = new LinkedList<>();
        int index = 0;
        char[] kCharArray = String.valueOf(k).toCharArray();
        int minLength = kLength <= num.length ? kLength : num.length;
        int next = 0;
        while (index < minLength) {
            int total = num[num.length - 1 - index] + (int)kCharArray[kCharArray.length - 1 - index] - '0' + next;
            result.addFirst(total % 10);
            next = total / 10;
            index++;
        }
        while (kCharArray.length == maxLength && index < maxLength) {
            int total = kCharArray[kCharArray.length - 1 - index] - '0' + next;
            result.addFirst(total % 10);
            next = total / 10;
            index++;
        }
        while (num.length == maxLength && index < maxLength) {
            int total = num[num.length - 1 - index] + next;
            result.addFirst(total % 10);
            next = total / 10;
            index++;
        }
        if (next == 1) {
            result.addFirst(1);
        }
        return result;
    }

    // 这个是行不通的，因为入参数字太大，所以会报错（测试用例限制）
//    public List<Integer> addToArrayForm(int[] num, int k) {
//        List<String> tempList = new ArrayList<>();
//        for (int i : num) {
//            tempList.add(String.valueOf(i));
//        }
//        long num1 = Long.parseLong(String.join("", tempList));
//        long total = num1 + k;
//        List<Integer> result = new ArrayList<>();
//        char[] charArray = String.valueOf(total).toCharArray();
//        for (char c : charArray) {
//            result.add(c - '0');
//        }
//        return result;
//    }

    public static void main(String[] args) {
        //int[] num = {1,2,0,0};
        //int k = 34;
        int[] num = {7};
        int k = 993;
        System.out.println(new Test1().addToArrayForm(num, k));
    }
}
